#define _CRT_SECURE_NO_WARNINGS
#include "Heap.h"

void swap(HPDataType* p1, HPDataType* p2) {
	HPDataType tem = *p1;
	*p1 = *p2;
	*p2 = tem;
}
void AdjustDown(HPDataType* a, int n, int parent) {
	int child = parent * 2 + 1;
	while (child < n) {
		if (child+1 < n && a[child] < a[child + 1]) {
			child++; 
		}
		if (a[child] > a[parent]) {
			swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else {
			break;
		}
	}
}
void HeapCreate(HP* hp, HPDataType* a, int n) {
	assert(hp);
	hp->a = (HPDataType*)malloc(sizeof(HPDataType) * n);
	if (hp->a == NULL) {
		perror("malloc fail");
		exit(-1);
	}
	memcpy(hp->a, a, sizeof(HPDataType) * n);
	hp->size = hp->capacity = n;

	for (int i = (n - 1 - 1) / 2; i >= 0; i--) {
		AdjustDown(hp->a, n, i);
	}
}
void HeapInit(HP* php) {
	assert(php);
	php->a = NULL;
	php->capacity = php->size = 0;
}
void HeapDestroy(HP* php) {
	assert(php);
	assert(php->a);
	free(php->a);
	php->capacity = php->size = 0;
}
void HeapPrint(HP* php) {
	assert(php);
	int i = 0;
	for (i = 0; i < php->size; i++) {
		printf("%d ", php->a[i]);
	}
	printf("\n");
}


void AdjustUp(HPDataType* a, int child) {
	int parent = (child - 1) / 2;
	while (child > 0) {
		if (a[parent] < a[child]) {
			swap(&a[parent], &a[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else {
			break;
		}
	}
}

void HeapPush(HP* php, HPDataType x) {
	assert(php);
	if (php->size == php->capacity) {
		int newCapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(php->a, sizeof(HPDataType) * newCapacity);
		if (tmp == NULL) {
			perror("malloc fail");
			exit(-1);
		}
		php->a = tmp;
		php->capacity = newCapacity;
	}
	php->a[php->size++] = x;
	AdjustUp(php->a, php->size-1);
}
void HeapPop(HP* php) {
	assert(php);
	assert(php->size > 0);
	swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;
	AdjustDown(php->a, php->size, 0);
}
HPDataType HeapTop(HP* php) {
	assert(php);
	assert(php->size>0);
	return php->a[0];
}
int HeapSize(HP* hp) {
	assert(hp);
	return hp->size;
}
bool HeapEmpty(HP* hp) {
	assert(hp);
	return hp->size == 0;
}